import { formatMinuteSecond } from '@/mxp-ui/mxp-tool/utils/time';
export default {
  data() {
    return {
      video: null,
      newProps: {},
      intervalId: null,
      intervalId2: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initVideoEvent();
    });
  },

  methods: {
    initVideoEvent() {
      this.video = document.getElementById(this.newProps.onlyID);
      // 监听视频事件
      this.video?.addEventListener('play', () => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'duration', duration: Math.floor(this.video?.duration) });
        this.$ownerInstance.callMethod('videoEvent', { type: 'play' });
        this.intervalId = setInterval(() => {
          this.$ownerInstance.callMethod('videoEvent', { type: 'seek', seek: Math.floor(this.video.currentTime) });
          if (this.video?.paused) {
            clearInterval(this.intervalId);
          }
        }, 1000);
      });

      this.video?.addEventListener('pause', () => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'pause' });
      });
      this.video?.addEventListener('ended', () => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'ended' });
      });
      this.video?.addEventListener('canplay', () => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'canplay', duration: Math.floor(this.video?.duration) });
      });

      this.video?.addEventListener('loadstart', () => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'loadstart' });
      });
      this.video?.addEventListener('error', (err) => {
        this.$ownerInstance.callMethod('videoEvent', { type: 'error', errrr: err });
      });

      this.video?.addEventListener('loadedmetadata', () => {
        this.$ownerInstance.callMethod('videoEvent', {
          type: 'loadedmetadata',
          width: this.video.videoWidth,
          height: this.video.videoHeight,
          duration: Math.floor(this.video?.duration),
        });
      });
      /** 视频总时时长 */
      let duration = 0;
      /** 初始触摸位置 */
      let startX = 0;
      /** 结束触摸位置 */
      let endX = 0;
      /** 初始触摸位置 */
      let startY = 0;
      /** 结束触摸位置 */
      let endY = 0;
      /** 视频初始播放时间 */
      let currentTime = 0;
      /** 最终快进后的时间 */
      let newCurrentTime = 0;
      /** 显示进度的遮罩 */
      let progressMaskDom = null;
      /** 快进或快退的时间Dom */
      let currTimeDom = null;
      /** 总时间Dom */
      let totalTimeDom = null;
      /** 进度条宽度 */
      let progressWidth = 200;
      /** 进度条Dom */
      let progressDom = 200;

      // 添加触摸事件监听器
      this.video?.addEventListener('touchstart', (e) => {
        startX = e.touches[0].clientX;
        endX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
        endY = e.touches[0].clientY;
        currentTime = Math.floor(this.video.currentTime);
        newCurrentTime = currentTime;
        duration = Math.floor(this.video.duration);
        progressMaskDom = document.getElementById(`${this.newProps.onlyID}__progress_mask`);
        currTimeDom = progressMaskDom.querySelector('.curr-time');
        totalTimeDom = progressMaskDom.querySelector('.total-time');
        progressWidth = progressMaskDom.querySelector('.progress-bg')?.offsetWidth || 200;
        progressDom = progressMaskDom.querySelector('.progress');
      });

      this.video?.addEventListener('touchmove', (e) => {
        if (typeof duration === 'number' && duration > 10 && typeof currentTime === 'number') {
          e.preventDefault(); // 防止默认行为，比如页面滚动
          endX = e.touches[0].clientX; // 获取当前触摸位置
          endY = e.touches[0].clientY; // 获取当前触摸Y位置
          const deltaX = endX - startX; // 计算水平移动距离
          const deltaY = endY - startY; // 计算垂直移动距离
          const rate = 20; // 调整速率（控制灵敏度）
          const timeDelta = (deltaX * rate) / this.video.offsetWidth; // 基于速率和视频宽度计算时间差
          newCurrentTime = currentTime + timeDelta; // 调整视频播放时间
          newCurrentTime = newCurrentTime < 0 ? 0 : newCurrentTime; // 防止小于 0
          newCurrentTime = newCurrentTime > duration ? duration : newCurrentTime; // 防止大于总时长
          const deltaXAbs = Math.abs(deltaX); // 水平移动距离的绝对值
          const deltaYAbs = Math.abs(deltaY); // 垂直移动距离的绝对值

          // 防止点击或为滑动也触发
          if (deltaXAbs > deltaYAbs && Math.abs(endX - startX) > 6) {
            progressMaskDom.style.display = 'flex';
            currTimeDom.innerHTML = formatMinuteSecond(Math.floor(newCurrentTime));
            totalTimeDom.innerHTML = formatMinuteSecond(duration);
            progressDom.style.width = `${(progressWidth / duration) * newCurrentTime}px`;
          }
        }
      });

      // 添加触摸事件监听器
      this.video?.addEventListener('touchend', () => {
        const deltaXAbs = Math.abs(endX - startX); // 水平移动距离的绝对值
        const deltaYAbs = Math.abs(endY - startY); // 垂直移动距离的绝对值

        // 防止点击或为滑动也触发
        if (deltaXAbs > deltaYAbs && Math.abs(endX - startX) > 6) {
          this.video.currentTime = newCurrentTime;
        }
        progressMaskDom.style.display = 'none';
      });
    },

    propsChange(val) {
      if (this.newProps.muted !== val.muted) {
        if (this.video) {
          this.video.muted = val.muted;
        }
      }
      this.newProps = val;
    },

    videoEventInfoChange(val) {
      if (this.video) {
        if (val.status === 'seek' && typeof val.seek === 'number') {
          this.video.currentTime = val.seek;
        } else if (val.status === 'pause') {
          this.video.pause();
        } else if (val.status === 'play') {
          this.video.play();
        } else if (val.status === 'stop') {
          this.video.stop();
          this.video.currentTime = 0;
        } else if (val.status === 'requestFullscreen') {
          this.video?.requestFullscreen?.();
        } else if (val.status === 'exitFullscreen') {
          this.video?.exitFullscreen?.();
        }
      }
    },
  },
};
